package com.pig4cloud.pig.module.controller.agent;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.module.api.entity.agent.AgentCompany;
import com.pig4cloud.pig.module.api.entity.location.City;
import com.pig4cloud.pig.module.api.entity.location.District;
import com.pig4cloud.pig.module.api.entity.location.Province;
import com.pig4cloud.pig.module.service.agent.IAgentCompanyService;
import com.pig4cloud.pig.module.service.location.CityService;
import com.pig4cloud.pig.module.service.location.DistrictService;
import com.pig4cloud.pig.module.service.location.ProvinceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

/**
 * 代理列Controller
 *
 * @author ruoyi
 * @date 2022-12-14
 */
@Validated
@Api(value = "代理列控制器", tags = {"代理列管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/company")
public class AgentCompanyController {

    private final IAgentCompanyService agentCompanyService;
    private final ProvinceService provinceService;

    private final CityService cityService;

    private final DistrictService districtService;

    /**
     * 查询代理列列表
     */
    @ApiOperation("查询代理列列表")
    @PreAuthorize("@pms.hasPermission('module:company:list')")
    @GetMapping("/list")
    public TableDataInfo<AgentCompany> list(@Validated AgentCompany agentCompany) {
        QueryWrapper<AgentCompany> qw = new QueryWrapper<>();
        if(agentCompany.getAgentName()!=null){
            qw.like("agent_name",agentCompany.getAgentName());
        }
        if (agentCompany.getAgentLeaderPhone()!=null){
            qw.eq("agent_leader_phone",agentCompany.getAgentLeaderPhone());
        }
        TableDataInfo<AgentCompany> td = PageUtils.buildDataInfo(agentCompanyService.page(PageUtils.buildPage(),qw));
        List<AgentCompany> list = td.getData();
        return td;
    }

    /**
     * 导出代理列列表
     */
    @ApiOperation("导出代理列列表")
    @PreAuthorize("@pms.hasPermission('module:company:export')")
    @SysLog("代理列")
    @GetMapping("/export")
    public List export(@Validated AgentCompany agentCompany) {
        List<AgentCompany> list = agentCompanyService.list();
        // ExcelUtil<AgentCompany> util = new // ExcelUtil<AgentCompany>(AgentCompany.class);
        return  list;// util.exportExcel(list, "代理列");
    }

    /**
     * 获取代理列详细信息
     */
    @ApiOperation("获取代理列详细信息")
    @PreAuthorize("@pms.hasPermission('module:company:query')")
    @GetMapping("/{id}")
    public R<AgentCompany> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        AgentCompany agentCompany = agentCompanyService.getById(id);
        String[] list = new String[2];

        if (ObjectUtil.isNotEmpty(agentCompany.getProvId())){
            list[0]= String.valueOf(agentCompany.getProvId());
        }
        if (ObjectUtil.isNotEmpty(agentCompany.getCityId())){
            list[1]= String.valueOf(agentCompany.getCityId());
        }
        if (ObjectUtil.isNotEmpty(agentCompany.getDistrictId())){
            list[2]= String.valueOf(agentCompany.getDistrictId());
        }

        agentCompany.setProvinceArray(list);
        /*String list;
        if (ObjectUtil.isNotEmpty(agentCompany.getDistrictId())){
            list= agentCompany.getProvId()+","+agentCompany.getCityId()+","+agentCompany.getDistrictId();
        }
        if (ObjectUtil.isNotEmpty(agentCompany.getCityId())){
            list= agentCompany.getProvId()+","+agentCompany.getCityId();
        }
        if (ObjectUtil.isNotEmpty(agentCompany.getProvId())){
            list= String.valueOf(agentCompany.getProvId());
        }*/
        return R.ok(agentCompany);
    }

    /**
     * 新增代理列
     */
    @ApiOperation("新增代理列")
    @PreAuthorize("@pms.hasPermission('module:company:add')")
    @SysLog("代理列")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody AgentCompany agentCompany) {
        String[] list = agentCompany.getProvinceArray();
        if(list!=null) {
            if (list.length > 0) {
                Province province = provinceService.findById(list[0]);
                if (province != null) {
                    agentCompany.setProvName(province.getProvinceName());
                    agentCompany.setProvId(Long.valueOf(province.getId()));
                }
                if (list.length > 1) {
                    City city = cityService.getById(list[1]);
                    if (city != null) {
                        agentCompany.setCityName(city.getCityName());
                        agentCompany.setCityId(Long.valueOf(city.getId()));
                    }
                }
                if (list.length > 2) {
                    District district = districtService.findById(list[2]);
                    if (district != null) {
                        agentCompany.setDistrictId(Long.valueOf(district.getDistrictName()));
                        agentCompany.setDistrictName(district.getDistrictName());
                    }
                }
            }
        }
        return R.okByRow(agentCompanyService.save(agentCompany) ? 1 : 0);
    }

    /**
     * 修改代理列
     */
    @ApiOperation("修改代理列")
    @PreAuthorize("@pms.hasPermission('module:company:edit')")
    @SysLog("代理列")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody AgentCompany agentCompany) {
        String[] list = agentCompany.getProvinceArray();
        if(list!=null) {
            if (list.length > 0) {
                Province province = provinceService.findById(list[0]);
                if (province != null) {
                    agentCompany.setProvName(province.getProvinceName());
                    agentCompany.setProvId(Long.valueOf(province.getId()));
                }
                if (list.length > 1) {
                    City city = cityService.getById(list[1]);
                    if (city != null) {
                        agentCompany.setCityName(city.getCityName());
                        agentCompany.setCityId(Long.valueOf(city.getId()));
                    }
                }
                if (list.length > 2) {
                    District district = districtService.findById(list[2]);
                    if (district != null) {
                        agentCompany.setDistrictId(Long.valueOf(district.getDistrictName()));
                        agentCompany.setDistrictName(district.getDistrictName());
                    }
                }
            }
        }
        return R.okByRow(agentCompanyService.updateById(agentCompany) ? 1 : 0);
    }

    /**
     * 删除代理列
     */
    @ApiOperation("删除代理列")
    @PreAuthorize("@pms.hasPermission('module:company:remove')")
    @SysLog("代理列")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(agentCompanyService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
